package com.lastcode6175.bluetoothremotecontrol

import android.util.Log
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.input.pointer.PointerInputChange
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlin.math.roundToInt

class TouchpadController {
    private val _isActive = MutableStateFlow(false)
    val isActive = _isActive.asStateFlow()

    private var sensitivity = 1.5f
    private var scrollSensitivity = 1.0f

    var onMouseMove: ((dx: Int, dy: Int) -> Unit)? = null
    var onMouseClick: (() -> Unit)? = null
    var onMouseScroll: ((amount: Int) -> Unit)? = null

    fun start() {
        if (_isActive.value) return
        _isActive.value = true
        Log.d("TouchpadController", "Touchpad mode started")
    }

    fun stop() {
        if (!_isActive.value) return
        _isActive.value = false
        Log.d("TouchpadController", "Touchpad mode stopped")
    }

    fun setSensitivity(value: Float) {
        sensitivity = value.coerceIn(0.5f, 3.0f)
    }

    fun setScrollSensitivity(value: Float) {
        scrollSensitivity = value.coerceIn(0.5f, 3.0f)
    }

    val onDrag: (change: PointerInputChange, dragAmount: Offset) -> Unit = { change, dragAmount ->
        if (_isActive.value) {
            val dx = (dragAmount.x * sensitivity).roundToInt()
            val dy = (dragAmount.y * sensitivity).roundToInt()

            if (dx != 0 || dy != 0) {
                onMouseMove?.invoke(dx, dy)
            }

            change.consume()
        }
    }

    fun onDragEnd() {
        // No specific action needed at the end of a drag, but the function is here for completeness
    }

    val onTap: () -> Unit = {
        if (_isActive.value) {
            onMouseClick?.invoke()
        }
    }

    fun onTransform(pan: Offset) {
        if (_isActive.value) {
            val scrollAmount = (pan.y * scrollSensitivity).roundToInt()
            if (scrollAmount != 0) {
                onMouseScroll?.invoke(scrollAmount)
            }
        }
    }
}